// CButtonSelect.cpp : Implementierungsdatei
//

#include "stdafx.h"
#include "Charplan.h"
#include "CButtonSelect.h"
#include ".\cbuttonselect.h"


// CButtonSelect

IMPLEMENT_DYNAMIC(CButtonSelect, CButton)
CButtonSelect::CButtonSelect()
{
    n_state = 0;
    n_state_max = 2;
}

CButtonSelect::~CButtonSelect()
{
}


BEGIN_MESSAGE_MAP(CButtonSelect, CButton)
    ON_CONTROL_REFLECT_EX(BN_CLICKED, OnBnClicked)
END_MESSAGE_MAP()


// CButtonSelect-Meldungshandler


BOOL CButtonSelect::PreCreateWindow(CREATESTRUCT& cs)
{
    cs.style |= BS_OWNERDRAW;
    return CButton::PreCreateWindow(cs);
}



void CButtonSelect::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
    CDC  *dc;
    CRect button_rect, text_rect, offset_text_rect;
    UINT state;

    dc    = CDC::FromHandle(lpDrawItemStruct->hDC);
    state = lpDrawItemStruct->itemState;

    button_rect.CopyRect(&lpDrawItemStruct->rcItem);

    text_rect = button_rect;
    offset_text_rect = text_rect;
    offset_text_rect.OffsetRect(1, 1);


    // Retrieve the button's caption
    const int bufSize = 125;
    TCHAR buffer[bufSize];
    GetWindowText(buffer, bufSize);


    //Background
    //dc->FillSolidRect(button_rect,GetSysColor(COLOR_BTNFACE));


    if (state & ODS_SELECTED)
    {
        dc->DrawFrameControl(button_rect, DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED);
    }
    else
    {
        dc->DrawFrameControl(button_rect, DFC_BUTTON, DFCS_BUTTONPUSH);
    }

    button_rect.bottom -=4;
    button_rect.right -=4;
    button_rect.top +=4;
    button_rect.left +=4;

    // Text
    dc->DrawText(buffer,button_rect,DT_SINGLELINE|DT_TOP|DT_CENTER);

    // Arrow
    /*        a   mx  a
       |      1      |
      my  |      2      |
      qy  |   3  4   |
          |---|
        sp
    */

    int mx = (button_rect.left+button_rect.right)/2;
    int my = (button_rect.top+button_rect.bottom)/2;
    int qy = (button_rect.bottom-button_rect.top)/4;

    // 1/3 space
    int w = button_rect.right-button_rect.left;
    int sp = w/(3*n_state_max);
    int tx = (w-2*sp)/(n_state_max-1);
    int a = button_rect.left+sp+tx*n_state;


    dc->MoveTo(mx,my);
    dc->LineTo(mx,my+qy);
    dc->LineTo(a,my+qy);
    dc->LineTo(a,my+qy*2);
    dc->LineTo(a-3,my+qy*2-3);
    dc->MoveTo(a,my+qy*2);
    dc->LineTo(a+3,my+qy*2-3);



    if (state & ODS_FOCUS)
    {
        button_rect.bottom++;
        button_rect.right++;
        button_rect.top--;
        button_rect.left--;
        dc->DrawFocusRect(button_rect);
    }

}


void CButtonSelect::SetMaxState(int nm)
{
    n_state_max = nm;
    Invalidate();
}


BOOL CButtonSelect::OnBnClicked()
{
    n_state = (n_state+1)%n_state_max;
    Invalidate();
    return FALSE;
}

int CButtonSelect::GetSelection()
{
    return n_state;
}

void CButtonSelect::SetSelection(int sel)
{
    if (n_state == sel) return;
    n_state = sel%n_state_max;
    Invalidate();
}